<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="../js/vue.js"></script>
    <script src="../js/jquery-3.6.0.js"></script>
    <title>Title</title>

</head>
<style>
    td{
        border: 1px solid #000;
        text-align: center;
    }
    img {
        max-width: 100px;
    }
</style>

<body>
<div id="app">
    <form>
        <div>
            图片目录:<input placeholder="输入图片目录" @change="changePath" name="path" v-model="path">
        </div>
        <div>
            保存目录:<input placeholder="保存目录" @change="changeOutput" name="output" v-model="output">
        </div>
        <div>
            压缩大小:<input placeholder="单位:M" @change="changeSize" type="number" name="size" @change="getLocationImgs"  v-model="size">
        </div>
        <div style="color:red;">
            仅仅支持JPG,JPEG格式;目录下的图不要放太多
        </div>
        <div>
            操作:
            <input type="button" @click="getLocationImgs" value="获取图">
            <input type="button" v-if="status==0" @click="allImgsToCompress('all')"value="全部压缩">
            <input type="button" v-if="status!=0" value="等待压缩结果...">
        </div>
        <div>
            排序:
            <input type="button" @click="getLocationImgs" value="获取图">
            <input type="button" v-if="status==0" @click="allImgsToCompress('all')"value="全部压缩">
            <input type="button" v-if="status!=0" value="等待压缩结果...">
        </div>
    </form>

    <table>
        <tr>
            <td>序号</td>
            <td>图</td>
            <td>文件名</td>
            <td>大小</td>
            <td>压缩为多少</td>
            <td>操作</td>
            <td>压缩后名称</td>
            <td>压缩后大小</td>
            <td>压缩后的图</td>
        </tr>
        <tr v-for="(img,i) in imgs">
            <td>
                {{i+1}}
            </td>
            <td>
                <a :href="img.name" target="_blank">
                <img  :src="img.name">
                </a>
            </td>
            <td><a :href="img.name" target="_blank" @click="copyToClip(img.name)">{{img.name}}</a></td>
            <td>{{bytesToSize(img.size)}}</td>
            <td>
                <p>{{img.compress}}%</p>
                <p><input name="" style="max-width: 40px" max="100" type="number" v-model="imgs[i].compress"></p>

            </td>
            <td>
                <input type="button" @click="removeImg(i)" value="删除">
                <br>
                <input type="button" @click="allImgsToCompress(i)" value="压缩">
            </td>
            <td ><a :href="img.res.res_img" @click="copyToClip(img.res.res_img)">{{img.res.res_img?img.res.res_img:""}}</a></td>
            <td >{{img.res.res_size?bytesToSize(img.res.res_size):""}}</td>
            <td>
                <a v-if="img.res.res_img" :href="img.res.res_img" target="_blank">
                    <img  :src="img.res.res_img">
                </a>
            </td>
        </tr>
    </table>
</div>
</body>
</html>

<script>
    var baseUrl = "http://127.0.0.1:520";
    var app = new Vue({
        el: '#app',
        data: {
            base : {
                wsUrl : "ws://127.0.0.1:520/echo",
            },
            path : "",
            output : "",
            imgs : [],
            size : 3,
            status : 0,
            ws : null,
            msgQueue : [],
            isSending : 0,
        },
        mounted : function () {
            let that = this;
            setTimeout(function () {
                that.getWebsocketConnect()
            },1000);

        },
        methods : {
            changeConfig : function (key,value) {
                let that = this;
                that.addMsgQueue(that.wsMsg("config.update",{key:key,value:value}))
            },
            changePath : function () {
                this.changeConfig("path",this.path)
            },
            changeOutput : function () {
                this.changeConfig("output",this.output)
            },
            changeSize : function () {
                this.changeConfig("size",this.size)
            },
            //获取配置
            getConfig : function () {
                let that = this
                that.addMsgQueue(that.wsMsg('config',{}))
            },//end getConfig()
            removeImg:function (index) {
                let that = this;
                if (!that.imgs[index])
                {
                    return;
                }
                that.imgs.splice(index,1)
            },
            getWebsocketConnect : function () {
                if ( !("WebSocket" in window))
                {
                    alert("您的浏览器不支持 WebSocket!");
                    return;
                }
                let that = this;
                if (!(that.ws instanceof WebSocket))
                {
                    that.ws = new WebSocket(that.base.wsUrl);
                    that.ws.onopen = that.wsOnOpen;
                    that.ws.onmessage = that.wsOnMessage;
                    that.ws.onclose = that.wsOnClose;
                    that.ws.onerror = that.wsOnError;
                }

                return that.ws;
            },
            wsOnOpen : function (evt) {
                let that = this;
                that.getConfig();
                that.wsSend();

                setInterval(function () {
                    if (that.msgQueue.length < 1)
                    {
                        that.addMsgQueue(that.wsMsg("ping",{}))
                    }
                },30000);

                setInterval(function (){
                    that.wsSend();
                },1000)
            },
            wsOnMessage : function (evt) {
                let that = this;
                let res = JSON.parse(evt.data);
                if (!res)
                {
                    return;
                }

                if (res.code !== 1)
                {
                    alert(res.msg);
                    return;
                }

                switch (res.action)
                {
                    case "imgs" :
                        that.revImgs(res.data)
                        break;
                    case "compress" :
                        that.compressData(res.data);
                        break;
                    case "config" :
                        that.showConfig(res);
                        break;
                }
            },
            wsOnClose : function (evt) {
                console.log("websocket已关闭",evt);
            },
            wsOnError : function (evt) {
                console.log("ws出错",evt);
            },

            wsMsg : function (action,data) {
                return JSON.stringify({
                    action : action,
                    data : data,
                })
            },
            addMsgQueue : function (msg) {
                let that = this;
                that.msgQueue.push(msg)
            },
            wsSend : function () {
                let that = this;
                if (that.isSending === 1)
                {
                    return;
                }
                that.isSending = 1;

                while (true)
                {
                    let msg = that.msgQueue.shift()
                    if (!msg)
                    {
                        break;
                    }
                    that.getWebsocketConnect().send(msg)
                }

                that.isSending = 0;
            },
            randomNum : function (minNum,maxNum){
                switch(arguments.length){
                    case 1:
                        return parseInt(Math.random()*minNum+1,10);
                    case 2:
                        return parseInt(Math.random()*(maxNum-minNum+1)+minNum,10);
                    default:
                        return 0;
                }
            },
            showConfig : function (res) {
                if (res.code !== 1)
                {
                    return;
                }
                let that = this;
                let data = res.data;
                let callback = function (field) {
                    if (data[field])
                    {
                        that[field] = data[field];
                    }
                }
                callback("path")
                callback("output")
                callback("size")


            },//end setConfig();
            revImgs:function (data) {
                let that = this;
                for (let i in data) {
                    setTimeout(function () {
                        if ( that.getKeyByImgField("md5",data[i].md5) !== -1 )
                        {
                            return;
                        }

                        data[i].compress = that.compressibility(data[i].size)
                        data[i].res = {
                            res_img : "",
                            res_size: ""
                        }
                        that.imgs.push(data[i]);
                    },that.randomNum(1000,4000))
                }

            },
            getLocationImgs : function () {
                let that = this;

                if (that.path === "")
                {
                    that.getConfig();
                    return;
                }

                that.imgs = [];

                that.addMsgQueue(that.wsMsg("imgs",{path:that.path}))

            },

            bytesToSize : function (bytes) {
                if (bytes === 0) return '0 B';
                var k = 1000, // or 1024
                    sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
                    i = Math.floor(Math.log(bytes) / Math.log(k));

                return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
            },
            compressibility : function (size) {
                let that = this;
                let s = that.size * 1024 * 1024;
                if (size < s)
                {
                    return 100;
                }
                return Math.floor(100 - (s * 100 / size) - 1.05);
            },
            sendCompressImgMsg : function (q,img,output) {
                let that = this;
                let msg = that.wsMsg("comporess",{q:q,img:img,output:output})
                that.addMsgQueue(msg)
            },

            validateBeforeCompress : function () {
                let that = this;
                if (that.status !== 0)
                {
                    return false;
                }
                if (that.output === "")
                {
                    that.getConfig();
                    alert("请输入保存目录");return false;
                }
                if (that.output === that.path)
                {
                    alert("目录一样会造成冲突！");return false;
                }
                return true;
            },

            getNeedCompressImgsByIndex : function (index = "all") {
                let imgs = [];
                let that = this;
                if (index === 'all')
                {
                    imgs = that.imgs;
                }else
                {
                    imgs.push(that.imgs[index])
                }
                return imgs;
            },

            allImgsToCompress : function (index = "all") {
                let that = this;
                if (that.validateBeforeCompress() !== true)
                {
                    return;
                }


                let imgs = that.getNeedCompressImgsByIndex(index);


                let callback = function (num) {
                    if (data.length >= num)
                    {
                        that.requestCompress(data)
                        data = [];
                    }
                }
                let data = [];
                for (const i in imgs)
                {
                    data.push({
                        img :imgs[i].name,
                        q :`${imgs[i].compress}`,
                    });
                    callback(that.randomNum(5,10));
                }
                callback(1);
            },

            requestCompress : function (p) {
                let that = this;
                let parmes = {
                    compress_imgs : p,
                    output : that.output,
                };
                that.status = 1;
                that.addMsgQueue(that.wsMsg("compress",parmes))
            },

            compressData : function (data) {
                let that = this;
                that.status = 0;
                for (const k in data)
                {
                    let index = that.getKeyByImgField("md5",data[k].source_md5);
                    if (index !== -1)
                    {
                        that.imgs[index].res = {
                            res_img : data[k].res_img,
                            res_size : data[k].res_size,
                        };
                    }


                }
                this.$forceUpdate();
                //console.log(that.imgs);
            },
            //key :this.imgs的key
            //value :要找的值
            getKeyByImgField :  function (key,value) {
                let that = this;
                for (const k in that.imgs)
                {
                    if (that.imgs[k][key] === value) {
                        return k;
                    }
                }
                return -1;
            },
            getKeyByImgName :  function (name) {
                let that = this;
                for (const k in that.imgs) {
                    if (that.imgs[k].name === name) {
                        return k;
                    }
                }
                return -1;
            },
            copyToClip : function(content) {
                let aux = document.createElement('input');
                aux.setAttribute('value', content);
                document.body.appendChild(aux);
                aux.select();
                document.execCommand('copy');
                document.body.removeChild(aux);
                alert("复制路径成功");

            }
        }
    });
</script>